package interceptor

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"strconv"
	"ylb/tool"
)

func TokenInterceptor() gin.HandlerFunc {

	return func(context *gin.Context) {
		token := context.GetHeader("token")
		//无token
		if token == "" {
			context.AbortWithStatusJSON(403, tool.Error("无token", nil))
			return
		}
		//token错误
		parseToken, er := tool.ParseToken(token)
		if er != nil {

			context.AbortWithStatusJSON(403, tool.Error("非法token", nil))
			return
		}
		i := parseToken.Data["userId"].(float64)

		session := sessions.Default(context)
		atoi, _ := strconv.Atoi(fmt.Sprintf("%1.0f", i))

		session.Set("userId", atoi)
		session.Save()
		context.Next()
	}
}
